package com.yh.musicplayer.data;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.media.MediaPlayer.OnCompletionListener;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.yh.musicplayer.MainActivity;
import com.yh.musicplayer.R;

import java.util.Random;


/**
 * Created by yxf on 2018/9/26.
 */

public class MusicService extends Service {
    //播放控制命令
    public static final int COMMAND_UNKNOW=-1;
    public static final int COMMAND_PLAY=0;
    public static final int COMMAND_PAUSE=1;
    public static final int COMMAND_STOP=2;
    public static final int COMMAND_RESUME=3;
    public static final int COMMAND_PREVIOUS=4;
    public static final int COMMAND_NEXT=5;
    public static final int COMMAND_CHECK_IS_PLAYING=6;
    public static final int COMMAND_SEEK_TO=7;
    public static final int COMMAND_RANDOM=8;
    public static final int COMMAND_PLAYMODE_CHANGED=9;
    //播放器状态
    public static final int STATUS_PLAYING=0;
    public static final int STATUS_PAUSED=1;
    public static final int STATUS_STOPPED=2;
    public static final int STATUS_COMPLETED=3;
    //广播标识
    public static final String BROADCAST_MUSICSERVICE_CONTROL="MusicService.ACTION_CONTROL";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS="MusicService.ACTION_UPDATE";

    //歌曲序号，从0开始
    private int number=0;
    private int status;

    private int playmode=2;
    //媒体播放类
    private MediaPlayer player=new MediaPlayer();
    //广播接收器
    private CommandReceiver receiver;
    private boolean phone=false;
    //内部类，接受广播并执行操作
    class CommandReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent){
            int command=intent.getIntExtra("command",COMMAND_UNKNOW);
            switch (command){
                case COMMAND_SEEK_TO:
                    seekTo(intent.getIntExtra("time",0));
                    break;
                case COMMAND_PLAY:
                    number=intent.getIntExtra("number",0);
                    play(number);
                    break;
                case COMMAND_PREVIOUS:
                    moveNumberToPrevious();
                    break;
                case COMMAND_NEXT:
                    moveNumberToNext();
                    break;
                case COMMAND_PAUSE:
                    pause();
                    break;
                case COMMAND_STOP:
                    stop();
                    break;
                case COMMAND_RESUME:
                    resume();
                    break;
                case COMMAND_CHECK_IS_PLAYING:
                    if(player!=null&&player.isPlaying()){
                        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                    }
                    else
                        sendBroadcastOnStatusChanged(MusicService.STATUS_PAUSED);//这句话关键
                    break;
                case COMMAND_RANDOM:
                    Random rand=new Random();
                    int i;
                    do{
                        i=rand.nextInt(MusicList.getMusicList().size());
                    }while(i==number);
                    number=i;
                    play(number);
                    break;
                case COMMAND_PLAYMODE_CHANGED:
                    playmode=intent.getIntExtra("playmode",0);
                    break;
                case COMMAND_UNKNOW:
                default:
                    break;
            }
        }

    }
    private void load(int number){
        try{
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();

        }catch (Exception e){
            e.printStackTrace();
        }
        player.setOnCompletionListener(completionListener);
    }
    //播放结束监听
    OnCompletionListener completionListener=new MediaPlayer.OnCompletionListener(){
        public void onCompletion(MediaPlayer player){
            if(player.isLooping()){
                replay();
            }else {
                sendBroadcastOnStatusChanged(MusicService.STATUS_COMPLETED);
            }
        }
    };
    private void play(int number){
        if(player!=null&&player.isPlaying()){
            player.stop();
        }
        load(number);
        player.start();
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }
    private void pause(){
        if(player.isPlaying()){
            player.pause();
            status=MusicService.STATUS_PAUSED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_PAUSED);
        }
    }
    private void stop(){
        if(status!=MusicService.STATUS_STOPPED){
            player.stop();
            status=MusicService.STATUS_STOPPED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_STOPPED);
        }

    }
    private void resume(){
        player.start();
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }
    private void replay(){
        player.start();
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    private void moveNumberToNext(){
        if((number)==MusicList.getMusicList().size()-1){
            Toast.makeText(MusicService.this,"已达到列表底端",Toast.LENGTH_SHORT).show();
        }else{
            ++number;
            play(number);
        }
    }

    private void moveNumberToPrevious(){
        if(number==0){
            Toast.makeText(MusicService.this,"已达到列表顶端",Toast.LENGTH_SHORT).show();
        }else{
            --number;
            play(number);
        }
    }
    private void seekTo(int time){
        player.seekTo(time);
    }

    private void bindCommandReceiver(){
        receiver=new CommandReceiver();
        IntentFilter filter=new IntentFilter(BROADCAST_MUSICSERVICE_CONTROL);
        registerReceiver(receiver,filter);
    }
    private void sendBroadcastOnStatusChanged(int status){
        Intent intent=new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status",status);
        if(status!=STATUS_STOPPED){
            intent.putExtra("time",player.getCurrentPosition());
            intent.putExtra("duration",player.getDuration());
            intent.putExtra("number",number);
            intent.putExtra("playmode",playmode);
            intent.putExtra("musicName", MusicList.getMusicList().get(number).getMusicName());
            intent.putExtra("musicArtist", MusicList.getMusicList().get(number).getMusicArtist());
            intent.putExtra("musicAlbum_id",MusicList.getMusicList().get(number).getAlbum_id());
        }
        sendBroadcast(intent);
    }
    @Nullable
    @Override

    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        bindCommandReceiver();
        status=MusicService.STATUS_STOPPED;
        TelephonyManager telephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }
    private final class MyPhoneListener extends PhoneStateListener{
        public void onCallStateChanged(int state,String incomingNumber){
            switch (state){
                case TelephonyManager.CALL_STATE_RINGING:
                    if(status==MusicService.STATUS_PLAYING){
                        pause();
                        phone=true;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if(phone==true){
                        resume();
                        phone=false;
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        if(player!=null){
           player.release();
        }
        super.onDestroy();
    }
}
